package com.example.demo.utils;

import com.example.demo.service.AuthService;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.io.File;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.Base64;

/**
 * @author Lucy
 * @create 2024-03-08 11:18
 */
public class ObjectRecognitionUtil {
    public static int advancedGeneral(String specifiedResult, File file) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general";
        try {
            byte[] imgData = Files.readAllBytes(file.toPath());
            String imgStr = Base64.getEncoder().encodeToString(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = AuthService.getAuth();
            String apiResult = HttpUtil.post(url, accessToken, param);
            int recognitionStatus = recognize(apiResult, specifiedResult);
            return recognitionStatus;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 2;
    }

    public static int recognize(String jsonResult, String specifiedResult) {
        Gson gson = new Gson();
        JsonObject resultObject = gson.fromJson(jsonResult, JsonObject.class);
        JsonArray resultArray = resultObject.getAsJsonArray("result");

        for (JsonElement resultElement : resultArray) {
            JsonObject result = resultElement.getAsJsonObject();
            String keyword = result.get("keyword").getAsString();
            double score = result.get("score").getAsDouble();

            if (keyword.contains(specifiedResult) || SemanticComparisonUtil.isSimilar(specifiedResult, keyword)) {
                if (score >= 0.5) {
                    return 1; // 识别成功
                } else {
                    return 2; // 识别失败
                }
            }
        }
        return 2; // 识别失败
    }
}
